<?php

/**
 * This is the model class for table "users".
 *
 * The followings are the available columns in table 'users':
 * @property integer $id
 * @property string $fullname
 * @property string $email
 * @property integer $phone
 * @property integer $gender
 * @property string $username
 * @property string $password
 * @property string $regdate
 * @property integer $status
 * @property integer $permission
 * @property string $avatar
 *
 * The followings are the available model relations:
 * @property Albums[] $albums
 * @property Articles[] $articles
 * @property Ratings[] $ratings
 * @property Videos[] $videoses
 */
class Users extends CActiveRecord
{
    private $_identity;
    public $rememberMe;
    public $confirmPassword;

	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Users the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'users';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('fullname, email, phone, gender, username, password, status, permission, confirmPassword', 'required', 'on' => 'register'),
            // rememberMe needs to be a boolean
            array('rememberMe', 'boolean'),
            array('username', 'unique', 'on' => 'register'),
            array('email', 'email'),
            // password needs to be authenticated
            array('username, password', 'required', 'on' => 'login'),
            array('password', 'authenticate', 'on' => 'login'),
            array(
                'confirmPassword', 'compare', 'compareAttribute' => 'password', 'on' => 'register'
            ),
			array('phone, gender, status, permission', 'numerical', 'integerOnly'=>true),
			array('fullname', 'length', 'max'=>30),
			array('email, avatar', 'length', 'max'=>255),
			array('username, password', 'length', 'max'=>64),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('id, fullname, email, phone, gender, username, password, regdate, status, permission, avatar', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'albums' => array(self::HAS_MANY, 'Albums', 'user_id'),
			'articles' => array(self::HAS_MANY, 'Articles', 'user_id'),
			'ratings' => array(self::HAS_MANY, 'Ratings', 'user_id'),
			'videoses' => array(self::HAS_MANY, 'Videos', 'user_id'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'id' => 'ID',
			'fullname' => 'Fullname',
			'email' => 'Email',
			'phone' => 'Phone',
			'gender' => 'Gender',
			'username' => 'Username',
			'password' => 'Password',
			'regdate' => 'Regdate',
			'status' => 'Status',
			'permission' => 'Permission',
			'avatar' => 'Avatar',
		);
	}

	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		// Warning: Please modify the following code to remove attributes that
		// should not be searched.

		$criteria=new CDbCriteria;

		$criteria->compare('id',$this->id);
		$criteria->compare('fullname',$this->fullname,true);
		$criteria->compare('email',$this->email,true);
		$criteria->compare('phone',$this->phone);
		$criteria->compare('gender',$this->gender);
		$criteria->compare('username',$this->username,true);
		$criteria->compare('password',$this->password,true);
		$criteria->compare('regdate',$this->regdate,true);
		$criteria->compare('status',$this->status);
		$criteria->compare('permission',$this->permission);
		$criteria->compare('avatar',$this->avatar,true);

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
            'pagination' => array(
                'pageSize'=>2,
            )
		));
	}

    /**
     * Authenticates the password.
     * This is the 'authenticate' validator as declared in rules().
     */
    public function authenticate($attribute,$params)
    {
        if(!$this->hasErrors())
        {
            $this->_identity=new UserIdentity($this->username,$this->password);
            if(!$this->_identity->authenticate())
                $this->addError('password','Incorrect username or password.');
        }
    }

    /**
     * Logs in the user using the given username and password in the model.
     * @return boolean whether login is successful
     */
    public function login()
    {
        if($this->_identity===null)
        {
            $this->_identity=new UserIdentity($this->username,$this->password);
            $this->_identity->authenticate();
        }
        if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
        {
            $duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
            Yii::app()->user->login($this->_identity,$duration);
            return true;
        }
        else
            return false;
    }

    protected function beforeSave() {
        if ($this->isNewRecord) {
            $this->regdate = date('Y-m-d');
            $this->password = md5($_POST['Users']['password']);
        }

        return parent::beforeSave();
    }
}